<?php

!defined('IN_APP') && exit('Access Denied');

class modelbase {
	
	protected $base;			//当前control类
	protected $db;				//mongo对象
	protected $modelname;	//当前model名字
	protected $collection;		//mongodb当前collection
	
    function __construct($base) {
        $this->base = $base;
        $this->db = $base->db;
        $this->modelname=substr(get_class($this),0,-5);
        $this->collection = $this->db->selectCollection($this->modelname);
    }
    
	/*得到mongodb中自动增长的id*/
	function get_autoincre_id($name= NULL){
		$name = $name ? $name : $this->modelname ;
		$update = array('$inc'=>array("id"=>1));
		$query = array('table_name' => $name);
		$command = array(
			'findandmodify'=>'autoincre_system', 'update'=>$update,
			'query'=>$query, 'new'=>true, 'upsert'=>true
		);
		$id = $this->db->command($command);
		return $id['value']['id'];
	}
	
	/*通用添加方法*/
	function insert($item){	
		$item['id'] = $this->get_autoincre_id();
		$this->collection->insert($item); 
		$this->writeLog();
	}

	/*通用更新方法
	$criteria 查询条件的数组
	$set		 更新字段的数组
	*/
	function update($criteria, $set){	
		$this->collection->update($criteria, array('$set' => $set) ); 
		$this->writeLog();
	}

	/*通用删除方法*/
	function remove($criteria){	
		$this->collection->remove($criteria); 
		$this->writeLog();
	}
	
	/*记录mongodb语句错误*/
	function writeLog(){
		file_put_contents('mongodb.log',var_export($this->db->lastError(),true), FILE_APPEND );
	}
	
	function findById($id){
		return $this->collection->findOne(array("id" => $id));
	}
	
	/*字段自动增加1*/
	function inc($id,$fieldName){
		$this->collection->update(array("id" => $id), array('$inc' => array($fieldName=>1)) ); 
	}
	
	 function query($params=array()){}
	 function queryAll($fetchAssociative=true,$params=array()){}
	 function queryRow($fetchAssociative=true,$params=array()){}
	 function queryScalar($params=array()){}//获取结果第一行第一列字段值
	 function queryColumn($params=array()){}//获取结果第一列的结果集
	 function deleteByPk($pk,$condition='',$params=array()){}
	 function deleteAll($condition='',$params=array()){}
	 function updateAll($attributes,$condition='',$params=array()){}
	 function exists($condition='',$params=array()){}
	 function count($condition='',$params=array()){}
}

